#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on Jul 25, 2014, by Junn
#
from django import forms
from regards.models import Regard, DateTip, NewRegardMessage
from utils.eggs import rename_file
from utils import images, files, eggs, logs
from django.utils import timezone
from users.models import User
import datetime
import settings

class RegardForm(forms.ModelForm):
    info = forms.CharField(required=False)
    pic = forms.ImageField(required=False)   #该属性对应request.FILES里的'pic'参数, 而非model中的CharFiled类型pic
    aud = forms.FileField(required=False)
    sent_time = forms.DateTimeField(required=False)
    
    def __init__(self, author, receiver, *args, **kwargs):
        self.author = author  # an user object
        self.receiver = receiver  # user object
        return super(RegardForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Regard
        fields = ('aud', 'aud_len', 'info', 'pic', 'sent_time')
        
    def clean_type(self):
        tp = self.cleaned_data.get('type')
        if tp and tp not in ('S', 'C', 'M'):
            raise forms.ValidationError(u'unkown regard type: %s' % tp)
        return tp
                
    def clean_info(self):
        info = self.cleaned_data.get('info', '')
        return info.strip()
          
    def clean_pic(self):
        return self.cleaned_data.get('pic', '')
        
    def clean_aud(self):
        aud = self.cleaned_data.get('aud')
        if aud:
            rename_file(aud)
        return aud    
    
    def clean_aud_len(self):  #TODO: check is digit
        return self.cleaned_data.get('aud_len', 0)
    
    def clean_sent_time(self):
        return self.cleaned_data.get('sent_time')

    
    def clean(self):
        data = self.cleaned_data
        info = data.get('info', '')
        pic = data.get('pic', '')
        aud = data.get('aud', '')
        aud_len = data.get('aud_len', 0)
        if not info.strip() and not pic and not aud:
            raise forms.ValidationError(u'还没有输入任何内容')
        if aud and not aud_len:
            raise forms.ValidationError(u'缺乏语音长度参数: aud_len')
        return data
        
    def save(self):
        data = self.cleaned_data
        regard = Regard(**data)
        regard.author = self.author
        regard.receiver = self.receiver
        
        if data.get('aud'):
            regard.aud = files.save_audio(data['aud'], eggs.gen_uuid1())
        else:
            regard.aud = ''    
        if data.get('pic'):
            regard.pic = images.save_image(data['pic'], eggs.gen_uuid1()+'.jpg', create_thumb=True)  #问候暂只支持上传一张图片
        else:
            regard.pic = ''
        regard.info = data.get('info', '')   
        regard.aud_len = data.get('aud_len') if data.get('aud_len') else 0   
            
        now = timezone.now()
        if not regard.sent_time:    #models.default=timezone.now 似乎没有起作用
            regard.sent_time = now
            
        regard.is_sent_now = True    
        if regard.sent_time and regard.sent_time > now:
            regard.is_sent_now = False
        
        regard.save()
        
        if regard.is_sent_now:     # 立即发送问候
            regard.send()
        return regard       
    
    
class TipForm(forms.ModelForm):
    
    def __init__(self, user, tid, *args, **kwargs):
        self.user = user
        self.tid = tid
        return super(TipForm, self).__init__(*args, **kwargs)    

    class Meta:
        model = DateTip
        fields = ('title', 'spec_date', 'notice_type', 'related_buddy', 'desc')
        
    def clean_tid(self):
        return self.cleaned_data.get('tid')
        
    def clean_title(self):
        title = self.cleaned_data.get('title')
        if not title:
            raise forms.ValidationError(u'title is null')
        return title.strip()
    
    def clean_spec_date(self):
        spec_date = self.cleaned_data.get('spec_date')
        if not spec_date:
            raise forms.ValidationError(u'spec_date is null')
        return spec_date
    
    def clean_notice_type(self):
        return self.cleaned_data.get('notice_type')
    
    def clean_related_buddy(self):
        return self.cleaned_data.get('related_buddy', 0)
    
    def clean_desc(self):
        return self.cleaned_data.get('desc', '')
    
    def save(self):
        data = self.cleaned_data
        
        try: 
            date_tip = DateTip.objects.get(id=int(self.tid))
            if date_tip.creator != self.user:  #TODO: refactoring this later, put in views layer...
                logs.warn('Datetip %s updated by unauthed-user' % self.tid)
            
            for attr in data.keys():  #对象属性逐个赋予新值 
                setattr(date_tip, attr, data.get(attr))
        except Exception, e:
            logs.war(__name__, eggs.lineno(), e)
            date_tip = DateTip(**data)
            
        date_tip.init_status()   
        date_tip.creator = self.user
        buddy_id = data.get('related_buddy', 0)
        if buddy_id:
            date_tip.related_buddy = User.objects.get_cached(buddy_id)
            
        if date_tip.is_triggerd_expired(): #新的或修改后的提醒, 若已过触发时间则立即放入消息队列进行触发
            try:
                msg, created = NewRegardMessage.objects.get_or_create(
                    sender=settings.SYS_TIP_SENDER, receiver=date_tip.creator.id
                )
                msg.set_extra_info(1, 'T', date_tip.title, date_tip.spec_date)
                date_tip.is_triggered = True
                date_tip.is_checked = False
            except Exception, e:
                logs.war(__name__, eggs.lineno(), e)
                pass
            
        date_tip.save()
        return date_tip
    
    
    
    
    